<template>
	<view class="btn-box" :style="[paddingBottomStyle]">
		<button class="submit-btn btn-transition-scale95" @click="handleSubmit()">提交</button>
	</view>
</template>

<script setup>
	import api from '@/api/index.js';
	import { toValue } from 'vue';
	import { storeToRefs } from 'pinia';
	import { usePostNeedStore } from '../store.js';

	const paddingBottomStyle = {
		'paddingBottom': getApp().globalData.safeAreaBottom > 0 ?
			getApp().globalData.safeAreaBottom + 'px' : '40rpx'
	};
	const store = usePostNeedStore();
	const { formData } = storeToRefs(store);

	// 校验规则
	const rules = [
		{ field: 'category', message: '请选择需求类型' },
		{ field: 'name', message: '请输入需求名称' },
		{ field: 'area', message: '请输入作业面积', isRequired: (category) => category == '1', arguments: 'category' },
		{ field: 'province_id', message: '请选择省份' },
		{ field: 'city_id', message: '请选择城市' },
		{ field: 'area_id', message: '请选择区县' },
		{ field: 'address', message: '请输入详细地址' },
	];

	// 提交数据
	const handleSubmit = async () => {
		// 校验是否输入或选择
		for (let i = 0; i < rules.length; i++) {
			const rule = rules[i];
			if (typeof rule.isRequired === 'function') {
				if (rule.isRequired(formData.value[rule.arguments]) && !formData.value[rule.field]) {
					uni.showNoneToast(rule.message);
					return;
				}
			} else if (!formData.value[rule.field]) {
				uni.showNoneToast(rule.message);
				return;
			}
		}

		const form = toValue(formData);
		form.budget = form.budget || 0; // 不填价格默认为0（面议）

		uni.showLoading({ title: '提交中...', mask: true });
		const post_api = formData.value.id ? api.c_need_api.edit : api.c_need_api.add;
		const res = await post_api(form).finally(() => setTimeout(uni.hideLoading, 100));

		uni.showSuccessToast('提交成功', () => {
			uni.$emit('refresh-my-needs-page'); // 刷新列表

			uni.redirectTo({
				url: '/pagesC-my/need-detail/index?id=' + (formData.value.id || res.data.data.id),
			});
		});
	}
</script>

<style lang="scss" scoped>
	.btn-box {
		padding: 80rpx 45rpx 0;

		.submit-btn {
			height: 88rpx;
			border-radius: 44rpx;
			font-size: 28rpx;
			color: white;
			text-align: center;
			line-height: 88rpx;
			background-color: #FE3333;
		}
	}
</style>